package com.lap.component.gateway.filter;

import com.lap.component.gateway.shared.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 记录日志
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
@Order(Constant.DEFAULT_ORDER + 20)
public class LoggingFilter implements GlobalFilter {

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    log.info("3.日志过滤器");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    log.info(
        "request:{},{}",
        exchange.getRequest().getURI().getPath(),
        exchange.getRequest().getQueryParams());
    return chain
        .filter(exchange)
        .then(
            Mono.fromRunnable(
                () -> {
                  int status = exchange.getResponse().getStatusCode().value();
                  stopWatch.stop();
                  log.info("status:{},time:{}", status, stopWatch);
                }));
  }
}
